package com.lezai.zookeeper.lock;

import org.I0Itec.zkclient.IZkDataListener;

import java.util.concurrent.CountDownLatch;

public class ZKExceptionLock extends ZkAbstractLock {
    private String lockPath;
    private CountDownLatch countDownLatch = new CountDownLatch(1);

    public ZKExceptionLock(String lockPath) {
        this.lockPath = PATH + "/" + lockPath;
    }
    public boolean tryLock() {
        try {
            zkClient.createEphemeral(lockPath);
            return true;
        }catch (Exception e){
            return false;
        }
    }

    public void waitLock() {
        zkClient.subscribeDataChanges(lockPath, new IZkDataListener() {
            public void handleDataChange(String s, Object o) throws Exception {
                System.out.println("---handleDataChange---");
            }

            public void handleDataDeleted(String s) throws Exception {
                countDownLatch.countDown();
            }
        });

        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void unLock(){
        zkClient.delete(lockPath);
    }
}